package com.weiaibenpao.demo.chislim.ui.activity.me;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetDialog;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.orhanobut.logger.Logger;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.weiaibenpao.demo.chislim.R;
import com.weiaibenpao.demo.chislim.api.Url;
import com.weiaibenpao.demo.chislim.base.BaseActivity;
import com.weiaibenpao.demo.chislim.bean.FansAttentionListBean;
import com.weiaibenpao.demo.chislim.bean.Moment;
import com.weiaibenpao.demo.chislim.bean.MyZoneBean;
import com.weiaibenpao.demo.chislim.bean.UserBean;
import com.weiaibenpao.demo.chislim.db.preferences.UserPreferences;
import com.weiaibenpao.demo.chislim.presenter.ZonePresenter;
import com.weiaibenpao.demo.chislim.ui.activity.moment.AttentionFansActivity;
import com.weiaibenpao.demo.chislim.ui.adapter.ZoneAdapter;
import com.weiaibenpao.demo.chislim.ui.widget.CircleImage;
import com.weiaibenpao.demo.chislim.ui.widget.MomentActionDialog;
import com.weiaibenpao.demo.chislim.ui.widget.MomentView;
import com.weiaibenpao.demo.chislim.ui.widget.ReportSelectDialog;
import com.weiaibenpao.demo.chislim.utils.Constant;
import com.weiaibenpao.demo.chislim.view.ZoneView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.OkHttpClient;
import okhttp3.Request;

public class UserZoneActivity extends BaseActivity<ZoneView, ZonePresenter> implements ZoneView, SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener, BaseQuickAdapter.OnItemChildClickListener {

    private ImageView mImg_bg;
    private TextView mTv_fans;
    private CircleImage mImg_user_head;
    private ImageView mImg_grade;
    private TextView mTv_user_grade;
    private TextView mTv_care;
    private TextView mTv_userName;
    private ImageView mImg_sex;
    private TextView mTv_userIntru;
    private Button mBtn_care;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.right_image)
    ImageView rightImg;
    private ZoneAdapter mAdapter;
    private int humorId;
    private int page = 1;
    private int mUserId;
    private UserPreferences userPreferences;
    private boolean isAttention;
    public static final String LIKE_SUCCESS = "点赞成功";
    public static final String UNLIKE_SUCCESS = "取消点赞成功";
    private View view;
    private final static int UP_SUCCESS = 12000;

    private View fanLayout,careLayout;
    private String path;
    private OkHttpClient client;
    private Request.Builder request;
    private String token;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 100:
                    if (!TextUtils.isEmpty(token)) {
                        uploadImageToQiNiu();
                    }
                    break;
                case UP_SUCCESS:
                    mPresenter.upDataInfo(mUserId, pathImg);

            }
        }
    };
    private String pathImg;
    private AlertDialog dialog;
    private int fanNumber,careNumber;
    private RequestOptions options;
    private View emptyView;

    @Override
    public int setLayoutResourceID() {
        return R.layout.activity_user_qzone;
    }

    @Override
    public void init(Bundle savedInstanceState) {

        EventBus.getDefault().register(this);
         options = new RequestOptions()
                .centerCrop()
//                .placeholder(Color.parseColor("#f6f6f6"))
                .diskCacheStrategy(DiskCacheStrategy.ALL);
        //发送七牛请求
        client = new OkHttpClient();
        request = new Request.Builder().url(Url.TOKEN_URL).get();
        userPreferences = UserPreferences.getInstance();
        mUserId = userPreferences.getInt(UserPreferences.USER_ID);//
        humorId = getIntent().getIntExtra(Constant.USER_ID, 0);//
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mSwipeRefreshLayout.setOnRefreshListener(this);
        initAdapter();
        doRefresh();


    }

    @Override
    protected void onResume() {
        super.onResume();

        if (mUserId != humorId) {
//           fanLayout.setClickable(false);
//           careLayout.setClickable(false);
            rightImg.setVisibility(View.VISIBLE);
            mImg_bg.setClickable(false);
            mBtn_care.setVisibility(View.VISIBLE);

        }else {
//            fanLayout.setClickable(true);
//            careLayout.setClickable(true);
            rightImg.setVisibility(View.GONE);
            mImg_bg.setClickable(true);
            mBtn_care.setVisibility(View.GONE);

        }


    }

    private void initAdapter() {
        emptyView = LayoutInflater.from(this).inflate(R.layout.layout_empty, recyclerView,false);
        ((TextView) emptyView.findViewById(R.id.tv_empty_new)).setText("赶快去发表动态吧！");
        view = initHeadView();
        mAdapter = new ZoneAdapter();
        recyclerView.setAdapter(mAdapter);
        mAdapter.setHeaderView(view);
        mAdapter.setHeaderAndEmpty(true);

        mAdapter.setOnLoadMoreListener(this, recyclerView);
        mAdapter.setOnItemChildClickListener(this);

    }

    private View initHeadView() {

        View view = LayoutInflater.from(this).inflate(R.layout.user_top_layout, null);
        fanLayout = view.findViewById(R.id.fan_layout);
        careLayout = view.findViewById(R.id.care_layout);


        mImg_bg = view.findViewById(R.id.img_bg);
        mTv_fans = view.findViewById(R.id.tv_fans);
        mImg_user_head = view.findViewById(R.id.img_user_head);
        mImg_grade = view.findViewById(R.id.img_grade);
        mTv_user_grade = view.findViewById(R.id.tv_user_grade);
        mTv_care = view.findViewById(R.id.tv_care);
        mTv_userName = view.findViewById(R.id.tv_userName);
        mImg_sex = view.findViewById(R.id.img_sex);
        mTv_userIntru = view.findViewById(R.id.tv_userIntru);
        mBtn_care = view.findViewById(R.id.btn_care);
        
        /**
         * 查看粉丝
         */
        fanLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AttentionFansActivity.startSelf(UserZoneActivity.this,0,humorId);
            }
        });
        /**
         * 查看关注列表
         */
        careLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AttentionFansActivity.startSelf(UserZoneActivity.this,1,humorId);

            }
        });

        mImg_bg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkPerMissions();
            }
        });
        mBtn_care.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPresenter.careOrUnCare(mUserId, humorId);
                isAttention = isAttention ? false : true;
            }
        });
        return view;
    }

    /**
     *
     * @param context
     * @param humorId  查看空间的Id
     */
    public static void startSelf(Context context, int humorId) {
        Intent intent = new Intent(context, UserZoneActivity.class);
        intent.putExtra(Constant.USER_ID, humorId);
        context.startActivity(intent);
    }

    @OnClick({R.id.left_image,R.id.right_image})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.left_image:
                finish();
                break;
            case R.id.right_image:
                if (humorId!=mUserId){
                    reportUser();

                }
                break;

        }
    }

    private void reportUser() {
        ReportSelectDialog reportSelectDialog = new ReportSelectDialog(UserZoneActivity.this);
        reportSelectDialog.setOnReportSelectListener(new ReportSelectDialog.OnReportSelectListener() {
            @Override
            public void onSelected(String content) {
                mPresenter.report(mUserId, humorId, 1, "举报");
            }
        });
        reportSelectDialog.show();
    }

    @Override
    public void onRefresh() {

        doRefresh();
    }

    private void doRefresh() {
        mSwipeRefreshLayout.setRefreshing(true);
        page = 1;
        mAdapter.setEnableLoadMore(false);//这里的作用是防止下拉刷新的时候还可以上拉加载
        doRequest();
    }

    private void doRequest() {
        mPresenter.getLatestMoments(humorId,mUserId, page);
    }

    @Override
    public void onLoadMoreRequested() {
        page++;
        doRequest();
    }


    @Override
    public ZonePresenter initPresenter() {
        return new ZonePresenter();
    }

    @Override
    public void onGetMomentListSuccess(MyZoneBean myZoneBean) {
        mSwipeRefreshLayout.setRefreshing(false);
        initView(myZoneBean);
        mAdapter.setEmptyView(emptyView);
        boolean isRefresh = page == 1;
        setData(isRefresh, myZoneBean);
}

    @Override
    public void onCareOrUnCareSuccess() {

        if (isAttention) {
            fanNumber++;
            mTv_fans.setText(fanNumber+"");
            mBtn_care.setText("已关注");
        } else {
            fanNumber--;
            mTv_fans.setText(fanNumber+"");
            mBtn_care.setText("+关注");
        }
    }

    private void setData(boolean isRefresh, MyZoneBean myZoneBean) {
        final int size = myZoneBean.getList() == null ? 0 : myZoneBean.getList().size();
        if (isRefresh) {
            mAdapter.setNewData(myZoneBean.getList());
        } else {
            if (size > 0) {
                mAdapter.addData(myZoneBean.getList());
            }
        }
        if (size < Constant.DEFAULT_PAGE_SIZE) {
            //第一页如果不够一页就不显示没有更多数据布局
            mAdapter.loadMoreEnd(isRefresh);

        } else {
            mAdapter.loadMoreComplete();
        }
    }


    @Subscribe(threadMode= ThreadMode.MAIN)
    public void eventMain(FansAttentionListBean.ListBean listBean){
        humorId=listBean.getUserId();
        doRefresh();

    }
    @Override
    public void onFail() {
        mSwipeRefreshLayout.setRefreshing(false);
    }

    @Override
    public void onDeleteSuccess(int position) {
        mAdapter.getData().remove(position);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onReportSuccess() {
        Toast.makeText(this, "感谢您的举报", Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onLikeOrUnlikeSuccess(String result, int position) {
        int originalNum = mAdapter.getData().get(position).getLikeNum();
        if (LIKE_SUCCESS.equals(result)) {
            mAdapter.getData().get(position).setNumber(MomentView.STATUS_LIKED);
            mAdapter.getData().get(position).setLikeNum(originalNum + 1);
        } else if (UNLIKE_SUCCESS.equals(result)) {
            mAdapter.getData().get(position).setNumber(MomentView.STATUS_UNLIKED);
            mAdapter.getData().get(position).setLikeNum(originalNum - 1);
        }
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void upDataInfoSuccess(UserBean userBean) {
//        Glide.with(this).load(pathImg).into(mImg_bg);
            UserPreferences.getInstance().putString(UserPreferences.USER_IMG_BG, userBean.getBgImage());
    }



    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, final int position) {
        if (view.getId() == R.id.more) {
            Logger.e("onItemChildClick------------more more more ");
            final Moment moment = mAdapter.getItem(position);
            handleClickMore(position, moment);
        } else if (view.getId() == R.id.like_container) {
            Logger.e("onItemChildClick------------like like like ");
            mPresenter.likeOrUnLike(mUserId, mAdapter.getData().get(position).getId(), position);
        }
    }

    private void handleClickMore(final int position, final Moment moment) {
        String action;
        if (UserPreferences.getInstance().getInt(UserPreferences.USER_ID) == moment.getUserId()) {
            action = MomentActionDialog.ACTION_DELETE;
        } else {
            action = MomentActionDialog.ACTION_REPORT;
        }
        MomentActionDialog momentActionDialog = new MomentActionDialog(this, action);
        momentActionDialog.setOnActionClickListener(new MomentActionDialog.OnActionClickListener() {
            @Override
            public void onActionClicked(String action) {
                Logger.e("onActionClicked----" + action);
                if (MomentActionDialog.ACTION_DELETE.equals(action)) {
                    mPresenter.deleteMoment(mUserId, moment.getId(), position);
                } else {
                    ReportSelectDialog reportSelectDialog = new ReportSelectDialog(UserZoneActivity.this);
                    reportSelectDialog.setOnReportSelectListener(new ReportSelectDialog.OnReportSelectListener() {
                        @Override
                        public void onSelected(String content) {
                            mPresenter.report(mUserId, moment.getId(), 0, content);
                        }
                    });
                    reportSelectDialog.show();
                }
            }
        });
        momentActionDialog.show();
    }


    /**
     * TextView tvFans;
     *
     * @BindView(R.id.img_grade) ImageView imgGrade;
     * @BindView(R.id.img_user_head) CircleImage imgUserHead;
     * @BindView(R.id.tv_user_grade) TextView tvUserGrade;
     * @BindView(R.id.tv_care) TextView tvCare;
     * @BindView(R.id.img_sex) ImageView imgSex;
     */
    private int sexId;

    private void initView(MyZoneBean myZoneBean) {
        fanNumber=myZoneBean.getFansNumber();
        careNumber=myZoneBean.getCaresNumber();
        mTv_fans.setText(fanNumber + "");
        mTv_care.setText(careNumber + "");

       int imgGrade= myZoneBean.getGrade()!=null?initGrade(myZoneBean.getGrade().getGradeNumber()): R.drawable.grade0;

        Glide.with(this).load(imgGrade).apply(options).into(mImg_grade);
        Glide.with(this).load(myZoneBean.getUser().getBgImage()).apply(options).into(mImg_bg);
        mTv_user_grade.setText(myZoneBean.getGrade()!=null? myZoneBean.getGrade().getGradeName():"暂无等级");
        Glide.with(this).load(myZoneBean.getUser().getUserImage()).apply(options).into(mImg_user_head);
        String userSex = myZoneBean.getUser().getUserSex();
        if (userSex.equals("男")) {
            sexId = R.drawable.icon_man;
        } else if (userSex.equals("女")) {
            sexId = R.drawable.icon_lady;
        }
        Glide.with(this).load(sexId).apply(options).into(mImg_sex);

        mTv_userName.setText(myZoneBean.getUser().getUserName());
        mTv_userIntru.setText(myZoneBean.getUser().getUserIntru());
        if (myZoneBean.getIsfans().equals("请关注")) {
            isAttention = false;
            mBtn_care.setText("+关注");
        } else {
            isAttention = true;
            mBtn_care.setText("已关注");
        }


    }

    private int initGrade(int gradeId) {
        if (gradeId == 1) {
            return R.drawable.grade1;
        }
        if (gradeId == 2) {
            return R.drawable.grade2;

        }
        if (gradeId == 3) {
            return R.drawable.grade3;

        } else if (gradeId == 4) {
            return R.drawable.grade4;

        } else if (gradeId == 5) {
            return R.drawable.grade5;

        } else if (gradeId == 6) {
            return R.drawable.grade6;

        } else if (gradeId == 7) {
            return R.drawable.grade7;

        }
        return R.drawable.grade0;
    }

    private void startCamera(boolean isOpenCamera) {
        // 进入相册 以下是例子：用不到的api可以不写
        if (isOpenCamera) {//打开相机
            // 单独拍照
            PictureSelector.create(UserZoneActivity.this)
                    .openCamera(PictureMimeType.ofImage())// 单独拍照，也可录像或也可音频 看你传入的类型是图片or视频
                    .maxSelectNum(1)
                    .enableCrop(true)// 是否裁剪 true or false
                    .freeStyleCropEnabled(true)// 裁剪框是否可拖拽 true or false
                    .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                    .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                    .withAspectRatio(1, 1)// int 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
//                .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
//                .selectionMedia()// 是否传入已选图片
                    .rotateEnabled(false) // 裁剪是否可旋转图片 true or false
                    .forResult(PictureConfig.CHOOSE_REQUEST);// 最大图片选择数量
        } else {//打开相册
            PictureSelector.create(UserZoneActivity.this)
                    .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                    .maxSelectNum(1)// 最大图片选择数量 int
                    .isCamera(true)// 是否显示拍照按钮 true or false
                    .enableCrop(true)// 是否裁剪 true or false
                    .freeStyleCropEnabled(true)// 裁剪框是否可拖拽 true or false
                    .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                    .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                    .withAspectRatio(3, 2)// int 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
//                .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
//                .selectionMedia()// 是否传入已选图片
                    .rotateEnabled(false) // 裁剪是否可旋转图片 true or false
                    .scaleEnabled(true)// 裁剪是否可缩放 true or false
                    .isCamera(false)// 是否显示拍照按钮 true or false
                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
        }

    }

    /**
     * 权限检查
     *
     * @param
     */
    public void checkPerMissions() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 1);
        } else {
//            createBottomSheetDialog(3);
            showPhotoDialog();

        }
    }

    private String[] items = {"拍照", "从手机相册选择", "取消"};

    private void showPhotoDialog() {
        //new 一个BottomSheetDialog对象
      final BottomSheetDialog  mBottomSheetDialog = new BottomSheetDialog(this);
        //获取要添加到BottomSheetDialog中的布局view
        View view = LayoutInflater.from(this).inflate(R.layout.pop_window_layout, null);
        view.findViewById(R.id.tv_camera).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBottomSheetDialog.dismiss();
                startCamera(true);
            }
        });
        view.findViewById(R.id.tv_photo).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBottomSheetDialog.dismiss();
                startCamera(false);

            }
        });
        view.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBottomSheetDialog.dismiss();
            }
        });

        //将布局添加到BottomSheetDialog中
        mBottomSheetDialog.setContentView(view);

        //显示
        mBottomSheetDialog.show();
//        new AlertDialog.Builder(this).setTitle("更换背景封面")
//                .setItems(items, new DialogInterface.OnClickListener() {
//
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        if (which == 0) {
//                            startCamera(true);
//                        } else if (which == 1) {
//                            startCamera(false);
//                        }
//                    }
//                }).setCancelable(true).create().show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 123:
                    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        // 检查该权限是否已经获取
                        int i = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);
                        // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                        if (i != PackageManager.PERMISSION_GRANTED) {
                            // 提示用户应该去应用设置界面手动开启权限
                            showDialogTipUserGoToAppSetting();
                        } else {
                            if (dialog != null && dialog.isShowing()) {
                                dialog.dismiss();
                            }

                        }
                        break;
                    }
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    LocalMedia localMedia = selectList.get(0);
                    if (localMedia.isCut()) {
                        path = localMedia.getCutPath();

                    } else {
                        path = localMedia.getPath();
                    }
                    getToken();
                    Glide.with(this).load(path).into(mImg_bg);

//                    userPreferences.getInt(UserPreferences.USER_ID)
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的

                    break;
            }
        }

    }

    private void getToken() {
        //发送七牛请求
//        builder.build();

        client.newCall(request.build()).enqueue(new okhttp3.Callback() {
            @Override
            public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {

                token = response.body().string();
                Logger.e("token==" + token);
                mHandler.sendEmptyMessage(100);
            }

            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
//                dialog.dismiss();
                Toast.makeText(UserZoneActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void uploadImageToQiNiu() {
        new Thread() {
            public void run() {
                // 图片上传到七牛 重用 uploadManager。一般地，只需要创建一个 uploadManager 对象
                UploadManager uploadManager = new UploadManager();
                uploadManager.put(path, null, token, new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        // res 包含hash、key等信息，具体字段取决于上传策略的设置。
                        if (info.isOK()) {
                            try {
                                // 七牛返回的文件名
                                pathImg = Url.PIC_URL + res.getString("key");
//                            qiNiuList.add(upImg);//将七牛返回图片的文件名添加到list集合
                                //list集合中图片上传完成后，发送handler消息回主线程进行其他操作
//                            if (qiNiuList.size() == selectList.size()) {
//                            Message obtain = Message.obtain();
//                            obtain.obj = upImg;
//                            obtain.what = UP_SUCCESS;
                                mHandler.sendEmptyMessage(UP_SUCCESS);
//                            }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else if (info.isServerError()) {
                            Toast.makeText(UserZoneActivity.this, "服务器异常，请稍后再试", Toast.LENGTH_SHORT).show();
                        }
                    }
                }, null);
            }
        }.start();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            showPhotoDialog();
        } else {
            showDialogTipUserGoToAppSetting();
        }
    }

    // 提示用户去应用设置界面手动开启权限
    private void showDialogTipUserGoToAppSetting() {
        String set = "请在-应用设置-权限管理\n允许东极圈使用相机权限，确保该功能的正常使用";
        dialog = new AlertDialog.Builder(this)
                .setTitle("相机权限不可用")
                .setMessage(set)
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 跳转到应用设置界面
                        goToAppSetting();
                        dialog.dismiss();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        Toast.makeText(UserZoneActivity.this, "请在应用管理中打开相关访问权限，确保该功能的正常使用", Toast.LENGTH_SHORT).show();
                    }
                }).setCancelable(false).show();
    }

    // 跳转到当前应用的设置界面
    private void goToAppSetting() {
        Intent intent = new Intent();

        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);

        startActivityForResult(intent, 123);
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
